<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Home extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }

    /**
     * 获取about表数据：
     * type：1 关于我们  2 客服电话  3 隐私协议   4 派逊天地  5 平台换货地址  6 尺寸图  7 注册协议
     * @return string
     */
    public function getAbout()
    {
		header("Access-Control-Allow-Origin: *");
        $type = input('type');
        $detail_ids = input('detail_ids');
        $res = Db::table('up_about')
            ->where('id',$type)
            ->find();
        if(isset($detail_ids) && $detail_ids){
            $codes = Db::table('up_self_order_detail')->where('detail_id', 'in',$detail_ids)->column('store_code');
            if($codes){
                $reals = [];
                foreach ($codes as $k => $v){
                    if($v) $reals[] = $v;
                }
                if($reals){
                    $reals = array_unique($reals);
                    if(count($reals) <= 1){
                        $resres = Db::table('up_cangku')->where('ck_code', $reals[0])->where('ck_status', 1)
                            ->field("concat(ck_name,' ',ck_phone) phone,ck_address content")->find();
                        if($resres) return json(['status'=>200,'msg'=>$resres]);
                    }
                }
            }
            $resres = Db::table('up_cangku')->where('ck_type', 2)->where('ck_status', 1)
                ->field("concat(ck_name,' ',ck_phone) phone,ck_address content")->find();
            if($resres) return json(['status'=>200,'msg'=>$resres]);
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * location 自动定位返回id：location
     * $location  地区名称
     */
    public function locationGet (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->where('level',1)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->where('level',2)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->where('level',3)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取首页数据：getHomeData
     * 轮播图、四个商品
     */
    public function getHomeData(){
        extract(input());
        $lunbo = Db::table('up_banner')
            ->where('banner_status',1)
            ->where('banner_type',1)
            ->field(['banner_id','banner_title','banner_img','banner_link','banner_object_id','banner_cate'])
            ->order('banner_sort ASC')
            ->page (1,5)
            ->select();
        $data = $this->getFourGoodsOrSearch(1,4);
        Db::table('up_u_user')->where('user_id',$user_id)->setField('user_update_time',date('Y-m-d H:i:s'));
        return json(['status'=>200,'msg'=>$lunbo,'four'=>$data]);
    }
    /**
     * 获取轮播图数据：getHomeData
     * 轮播图、四个商品
     */
    public function getBannerByType(){
        extract(input());
        if(!isset($type)) $type = 1;
        $lunbo = Db::table('up_banner')
            ->where('banner_status',1)
            ->where('banner_type',$type)
            ->field(['banner_id','banner_title','banner_img','banner_link','banner_object_id','banner_cate'])
            ->order('banner_sort ASC')
            ->page (1,5)
            ->select();
        return json(['status'=>200,'msg'=>$lunbo]);
    }
    /**
     * 首页搜索
     * page
     * keyword
     */
    public function getSearchGoods(){
        extract(input());
        if(!isset($page)){
            $page = 1;
        }
        $data = $this->getFourGoodsOrSearch($page,10,$keyword);
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 商品列表（针对某个学校的也是这个）
     * page
     * keyword
     */
    public function getGoodsByType(){
        extract(input());
        if(!isset($sort) || empty($sort)){
            $sort = '';
        }
        if(!isset($school) || empty($school)){
            $school = '';
        }
        if($sort){
            if($sort == 1){
                if($high == 1){ //1从高到低  2从低到高
                    $order = 'good_price DESC,good_create_time DESC';
                }else{
                    $order = 'good_price ASC,good_create_time DESC';
                }
            }elseif($sort == 2){
                $order = 'good_sales DESC,good_create_time DESC';
            }elseif($sort == 3){
                $order = 'good_click DESC,good_create_time DESC';
            }else{
                $order = 'good_create_time DESC';
            }
        }else{
            $order = 'good_sort ASC,good_create_time DESC';
        }
        $data = $this->getFourGoodsOrSearch($page,10,'',$order,$school);
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取四个商品
     */
    public function getFourGoodsOrSearch($page,$limit,$key='',$order='',$school=''){
        $where = [
            'good_status' => 1
        ];
        if($key){
            $where['good_name|school_name'] = ['like','%'.$key.'%'];
        }
        if(!$order){
            $order = 'good_sort ASC,good_create_time DESC';
        }
        if($school){
            $where['good_school'] = $school;
        }

        $field = 'good_id,school_name_remark good_name,good_price,good_thumb,school_name,school_id';
        $data = Db::table('up_self_goods')->alias('g')
            ->join('up_school s','g.good_school=s.school_id','LEFT')
            ->where($where)
//            ->where('good_stock','>',0)
            ->field($field)
            ->order($order)
            ->page ($page,$limit)
            ->select();
        return $data;
    }


    /**
     * 获取轮播图内容：getBannerContent
     */
    public function getBannerContent(){
        extract(input());
        $data = Db::table('up_banner')
            ->where('banner_id',$banner_id)
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 商品详情
     */
    public function getGoodDetail()
    {
        extract(input());
        header("Access-Control-Allow-Origin:*");
        Db::table('up_self_goods')->where('good_id',$good_id)->setInc('good_click');
        $good = Db::table('up_self_goods')->alias('g')
            ->join('up_school s','g.good_school=s.school_id','LEFT')
            ->where('good_id',$good_id)
            ->find();
        if($good['good_status'] != 1){ //非上架不展示
            return json(['status'=>0,'msg'=>'此商品已下架']);

        }
        if($good['good_image']){
            $good['good_image'] = explode(',',$good['good_image']);
        }else{
            $good['good_image'] = [];
        }
        //是否收藏
        $good['like'] = 0;
        $like = Db::table('up_like_goods')
            ->where('l_user_id',$user_id)
            ->where('l_good_id',$good_id)
            ->where('l_type',1)
            ->find();
        if($like){
            $good['like'] = 1;
        }
        //一条评价
        $comment = Db::table('up_self_goods_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_good_id',$good_id)
            ->where('comment_type',1)
            ->order('comment_time desc')
            ->field('gc.*,user_username,user_image,user_phone')
            ->find();
        if(!$comment){
            $comment = [];
        }else{
            if($comment['comment_image']){
                $comment['comment_image'] = explode(',',$comment['comment_image']);
            }
        }
        //规格和对应价格
        $guige = json_decode($good['good_guige'],true);
        $guige_price = Db::table('up_self_goods_attr')
            ->where('goods_id',$good_id)
            ->where('is_delete',0)
            ->select();
//        $good['good_content'] = '<p style="text-align: center;"><img src="http://qiniu.panson.com/size/size.png"></p>' . $good['good_content'];
        return json(['status'=>200,'msg'=>$good,'comment'=>$comment,'guige'=>$guige,'guige_price'=>$guige_price]);
    }
    /**
     * 获取商品评价
     */
    public function getGoodComment()
    {
        extract(input());
        //一条评价
        $comment = Db::table('up_self_goods_comment')->alias('gc')
            ->join('up_u_user u','gc.comment_user_id=u.user_id','LEFT')
            ->where('comment_good_id',$good_id)
            ->where('comment_type',1)
            ->order('comment_time desc')
            ->page($page,15)
            ->field('gc.*,user_username,user_image,user_phone')
            ->select();
        foreach ($comment as $k=>$v){
            if($v['comment_image']){
                $comment[$k]['comment_image'] = explode(',',$v['comment_image']);
            }else{
                $comment[$k]['comment_image'] = [];
            }
        }

        return json(['status'=>200,'msg'=>$comment]);
    }

    /**
     * 喜欢或者不喜欢商品
     */
    public function likeGoodsOrNot()
    {
        extract(input());
        $have = Db::table('up_like_goods')
            ->where('l_type',1)
            ->where('l_good_id',$good_id)
            ->where('l_user_id',$user_id)
            ->find();
        if($have){
            $res = Db::table('up_like_goods')
                ->where('l_type',1)
                ->where('l_good_id',$good_id)
                ->where('l_user_id',$user_id)
                ->delete();

        }else{
            $res = Db::table('up_like_goods')->insert([
                'l_type'=>1,
                'l_good_id'=>$good_id,
                'l_user_id'=>$user_id,
                'l_time'=>date('Y-m-d H:i:s')
            ]);
        }
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        set_time_limit(0);
//        $area = file_get_contents('static/area.json');
//        $area2 = json_decode($area,true);
//        return json($area2);
        set_time_limit(0);
        $pro = Db::table('up_area')
            ->where('pid',0)
//            ->where('district_id',1001)
            ->field('district_id id,district name')
            ->order('CRI_SORT')
            ->select();
        foreach($pro as $k=>$v){
            $pro[$k]['parentId'] = 0;
            $city = Db::table('up_area')
                ->where('pid',$v['id'])
                ->where('level',2)
                ->field('district_id id,district name,pid parentId')
                ->select();
            foreach ($city as $kk=>$vv){
                $city[$kk]['sub'] = Db::table('up_area')
                    ->where('pid',$vv['id'])
                    ->where('level',3)
                    ->field('district_id id,district name,pid parentId')
                    ->select();
            }
            $pro[$k]['sub'] = $city;
        }
        return json($pro);
    }

}